<template>
  <div class="homework-history">
    <div class="layout-container">
      <!-- 侧边栏 -->
      <!-- <div class="sidebar">
        <div class="sidebar-header">
          <h3>习题管理</h3>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="sidebar-menu"
          @select="handleMenuSelect"
        >
          <el-menu-item index="generator">
            <el-icon><Edit /></el-icon>
            <span>习题定制</span>
          </el-menu-item>
          <el-menu-item index="history">
            <el-icon><List /></el-icon>
            <span>历史记录</span>
          </el-menu-item>
          <el-menu-item index="hot">
            <el-icon><Star /></el-icon>
            <span>热点考题</span>
          </el-menu-item>
          <el-menu-item index="mistakes">
            <el-icon><Warning /></el-icon>
            <span>高频错题</span>
          </el-menu-item>
        </el-menu>
      </div> -->

      <!-- 主内容区 -->
      <div class="main-content">
        <el-card class="history-card">
          <template #header>
            <div class="card-header">
              <h2>历史记录</h2>
              <div class="header-controls">
                <span class="page-info">第 {{ currentPage }} 页 / 每页15条 / 共 {{ total }} 条</span>
                <div class="custom-pagination">
                  <el-button 
                    size="small" 
                    :disabled="currentPage <= 1" 
                    @click="jumpToPage(currentPage - 1)"
                  >
                    上一页
                  </el-button>
                  <span class="page-number">{{ currentPage }}</span>
                  <el-button 
                    size="small" 
                    :disabled="currentPage >= Math.ceil(total / 15)" 
                    @click="jumpToPage(currentPage + 1)"
                  >
                    下一页
                  </el-button>
                </div>
                <el-button type="primary" @click="fetchHistoryRecords" :loading="loading">刷新</el-button>
              </div>
            </div>
          </template>
          <div class="history-list" v-loading="loading">
            <div v-if="historyRecords.length === 0 && !loading" class="empty-tip">
              暂无历史记录
            </div>
            <div v-for="(record, index) in historyRecords" 
                 :key="index" 
                 class="history-item"
                 @click="viewHistoryDetail(record)">
              <div class="history-item-header">
                <span class="history-subject">【{{ record.subject }}】{{ formatQuestionType(record.type) }}</span>
                <span class="history-time">{{ record.time }}</span>
              </div>
              <div class="history-content">{{ record.content }}</div>
              <div class="history-item-footer">
                <el-tag size="small" :type="getDifficultyType(record.difficulty)">
                  {{ getDifficultyLabel(record.difficulty) }}
                </el-tag>
                <span class="topic-tag">{{ record.topic }}</span>
              </div>
            </div>
            <div class="bottom-space"></div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Edit, List, Star, Warning } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { exerciseApi } from '@/api'
import request from '@/utils/request'

const router = useRouter()
const activeMenu = ref('history')
const historyRecords = ref([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(15)
const total = ref(10)

const handleMenuSelect = (index) => {
  activeMenu.value = index
  if (index === 'generator') {
    router.push('/homework/generator')
  }
}

// 直接跳转到指定页面
const jumpToPage = (page) => {
  console.log('跳转到页面:', page)
  if (page < 1 || page > Math.ceil(total.value / 15)) {
    console.log('页码超出范围，忽略')
    return
  }
  
  if (page === currentPage.value) {
    console.log('当前已是第', page, '页，忽略')
    return
  }
  
  // 更新页码
  currentPage.value = page
  
  // 显示加载中
  loading.value = true
  historyRecords.value = []
  
  // 显示提示
  ElMessage.info({
    message: `正在加载第${page}页数据...`,
    duration: 1000
  })
  
  // 直接调用获取数据
  fetchHistoryRecordsForPage(page)
}

// 为特定页面获取历史记录，绕过缓存
const fetchHistoryRecordsForPage = async (page) => {
  loading.value = true
  
  try {
    // 直接使用原始axios请求，避免可能的缓存问题
    const timestamp = new Date().getTime()
    const response = await request({
      url: `/api/exercises/history?_t=${timestamp}`,
      method: 'get',
      params: {
        teacherId: localStorage.getItem('teacherId'),
        page: page,
        size: 15
      }
    })
    
    console.log(`获取第${page}页数据响应:`, response)
    
    // 处理响应
    if (response.data && response.data.code === 200 && Array.isArray(response.data.data)) {
      // 记录ID，检查是否有变化
      const recordIds = response.data.data.map(item => item.id).join(',')
      console.log(`第${page}页记录ID: ${recordIds}`)
      
      historyRecords.value = response.data.data.map(item => ({
        id: item.id,
        subject: item.subject,
        topic: item.topic,
        content: item.content,
        difficulty: item.difficulty,
        type: item.questionType,
        answer: item.answer,
        analysis: item.analysis,
        time: new Date(item.createdTime).toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })
      }))
      
      total.value = response.data.total || historyRecords.value.length
    } else {
      console.error('响应格式不正确:', response)
      ElMessage.error('获取数据失败：格式不正确')
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
    ElMessage.error('获取历史记录失败: ' + (error.message || '未知错误'))
  } finally {
    loading.value = false
  }
}

// 添加全局样式
const globalStyle = document.createElement('style');
globalStyle.textContent = `
.exercise-detail-dialog .el-message-box__content {
  max-height: 70vh;
  overflow-y: auto;
}
.exercise-detail-dialog .el-message-box {
  width: 80%;
  max-width: 600px;
}
.exercise-detail-dialog .el-message-box__message p {
  margin: 0;
  line-height: 1.6;
}
`;
document.head.appendChild(globalStyle);

// 查看历史记录详情
const viewHistoryDetail = (item) => {
  // 解析题目内容和选项
  let questionText = item.content;
  let optionsHtml = '';
  
  if (item.type === 'multiple-choice' && item.content) {
    // 尝试提取题干和选项
    const lines = item.content.split('\n').filter(line => line.trim());
    
    // 第一行通常是题干
    if (lines.length > 0) {
      questionText = lines[0].trim();
      
      // 尝试从剩余行提取选项
      let hasOptions = false;
      optionsHtml = '<strong>选项：</strong><br>';
      
      for (let i = 1; i < lines.length; i++) {
        const line = lines[i].trim();
        // 匹配 A. 内容 或 A：内容 或 A 内容 等格式
        if (line.length > 1 && 'ABCD'.includes(line[0]) && (line[1] === '.' || line[1] === ':' || line[1] === '：' || line[1] === ' ')) {
          hasOptions = true;
          const option = line[0];
          const content = line.substring(line.indexOf(option) + 1).replace(/^[.:\s：]+/, '').trim();
          optionsHtml += `<div style="margin-left:15px;margin-bottom:5px;"><span style="font-weight:bold;margin-right:5px;">${option}.</span> ${content}</div>`;
        }
      }
      
      // 如果没有找到选项，尝试其他解析方法
      if (!hasOptions) {
        // 正则表达式匹配各种选项格式
        const optionRegex = /([A-D])[.:\s：]\s*(.*?)(?=\s*[A-D][.:\s：]|$)/gs;
        let match;
        let fullContent = item.content;
        
        while ((match = optionRegex.exec(fullContent)) !== null) {
          hasOptions = true;
          optionsHtml += `<div style="margin-left:15px;margin-bottom:5px;"><span style="font-weight:bold;margin-right:5px;">${match[1]}.</span> ${match[2].trim()}</div>`;
        }
      }
      
      // 如果仍然没有找到选项，不显示选项部分
      if (!hasOptions) {
        optionsHtml = '';
      }
    }
  }
  
  ElMessageBox.alert(
    `<div style="font-size:15px;line-height:1.6;">
      <div style="margin-bottom:15px;"><strong>题目：</strong>${questionText}</div>
      ${optionsHtml ? `<div style="margin-bottom:15px;">${optionsHtml}</div>` : ''}
      <div style="margin-bottom:8px;"><strong>科目：</strong>${item.subject}</div>
      <div style="margin-bottom:8px;"><strong>知识点：</strong>${item.topic}</div>
      <div style="margin-bottom:8px;"><strong>难度：</strong>${getDifficultyLabel(item.difficulty)}</div>
      <div style="margin-bottom:8px;"><strong>题型：</strong>${formatQuestionType(item.type)}</div>
      <div style="margin-bottom:8px;"><strong>答案：</strong>${item.answer || '暂无'}</div>
      <div style="margin-bottom:8px;"><strong>解析：</strong>${item.analysis || '暂无'}</div>
      <div><strong>创建时间：</strong>${item.time}</div>
    </div>`,
    '习题详情',
    {
      dangerouslyUseHTMLString: true,
      confirmButtonText: '关闭',
      customClass: 'exercise-detail-dialog'
    }
  )
}

// 格式化题型
const formatQuestionType = (type) => {
  const typeMap = {
    'multiple-choice': '选择题',
    'fill-blank': '填空题',
    'true-false': '判断题',
    'short-answer': '简答题'
  };
  return typeMap[type] || type;
}

// 获取难度标签颜色类型
const getDifficultyType = (difficulty) => {
  const types = {
    easy: 'success',
    medium: 'warning',
    hard: 'danger'
  }
  return types[difficulty] || 'info'
}

// 获取难度标签文本
const getDifficultyLabel = (difficulty) => {
  const labels = {
    easy: '简单',
    medium: '中等',
    hard: '困难'
  }
  return labels[difficulty] || '未知'
}

// 获取历史记录（默认获取第一页）
const fetchHistoryRecords = async () => {
  currentPage.value = 1
  fetchHistoryRecordsForPage(1)
}

onMounted(() => {
  // 加载第一页历史记录数据
  fetchHistoryRecords()
})
</script>

<style scoped>
.homework-history {
  padding: 20px;
  max-width: 1600px;
  margin: 0 auto;
  margin-top: 60px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.layout-container {
  display: flex;
  gap: 20px;
  min-height: calc(100vh - 100px);
  margin-top: -120px;
  align-items: flex-start;
  flex: 1;
}

.sidebar {
  width: 240px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  position: sticky;
  top: 80px;
  height: calc(100vh - 100px);
  overflow-y: auto;
}

.sidebar-header {
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
  font-weight: 600;
}

.sidebar-menu {
  border-right: none;
}

.main-content {
  flex: 1;
  min-width: 0;
  height: auto;
  overflow-y: visible;
  padding: 20px;
}

.history-card {
  height: auto;
  min-height: calc(100vh - 140px);
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.history-list {
  max-height: calc(100vh - 190px);
  height: auto;
  overflow-y: auto;
  padding: 10px 10px 25px 10px;
  margin-bottom: 20px;
}

.history-item {
  padding: 15px;
  border-bottom: 1px solid #ebeef5;
  cursor: pointer;
  transition: all 0.3s;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.history-item:hover {
  background-color: #f5f7fa;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.history-item:last-child {
  margin-bottom: 30px; /* 为最后一项增加额外的底部边距 */
}

.history-item-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.history-subject {
  font-weight: 600;
  color: #303133;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.history-content {
  font-size: 14px;
  color: #606266;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  margin-bottom: 8px;
}

.history-item-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.topic-tag {
  font-size: 12px;
  color: #909399;
  background-color: #f4f4f5;
  padding: 2px 8px;
  border-radius: 4px;
}

.empty-tip {
  text-align: center;
  padding: 40px 0;
  color: #909399;
  font-size: 14px;
}

/* 添加滚动条样式 */
.history-list::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-track {
  background-color: transparent;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  border-bottom: 1px solid #ebeef5;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  color: #303133;
  font-weight: 600;
}

.header-controls {
  display: flex;
  align-items: center;
  gap: 15px;
}

.page-info {
  font-size: 13px;
  color: #606266;
  white-space: nowrap;
}

.custom-pagination {
  display: flex;
  align-items: center;
  gap: 10px;
  background: #f5f7fa;
  padding: 5px 10px;
  border-radius: 4px;
}

.page-number {
  font-size: 14px;
  font-weight: bold;
  color: #409EFF;
  min-width: 24px;
  text-align: center;
}

.bottom-space {
  height: 30px;
  width: 100%;
}
</style> 